﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using ESSManageService.Common.Helper;
using ESSManageService.Common.Tools;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Sinks.SystemConsole.Themes;
using SqlSugar;

namespace ESSManageService.Serilog
{
    public static class SeriLogger
    {
        private static readonly string LogDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");

        static SeriLogger()
        {
            StartLog();
        }

        private static void StartLog()
        {
            
        }

        public static void WriteLogDebug(string message)
        {
            Log.Debug(message);
        }

        public static void WriteLogInfo(string message)
        {
            Log.Information(message);
        }

        public static void WriteLogWarn(string message)
        {
            Log.Warning(message);
        }

        public static void WriteLogError(string message, Exception ex = null)
        {
            Log.Error(ex, message);
        }

        public static void WriteLogFatal(string message, Exception ex = null)
        {
            Log.Fatal(ex, message);
        }

        public static void WriteSql(string message)
        {
            Log.Verbose(message);
        }

        /// <summary>
        /// 日志清除
        /// </summary>
        /// <param name="RetentionPeriod">有效期天数</param>
        public static void CleanLogs(int RetentionPeriod)
        {
            if (!Directory.Exists(LogDirectory))
            {
                Console.WriteLine("日志文件地址不存在.");
                return;
            }
            var logFiles = Directory.GetFiles(LogDirectory);

            foreach (var logFile in logFiles)
            {
                try
                {
                    var fileInfo = new FileInfo(logFile);
                    if (fileInfo.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(RetentionPeriod)))
                    {
                        fileInfo.Delete();
                        Console.WriteLine($"Deleted log file: {fileInfo.Name}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to delete log file: {logFile}. Error: {ex.Message}");
                }
            }
        }
    }
}
